import { useEffect, useState } from 'react'
import { getArticleList,updataArticle,deleteArticle } from '../../../src/api/publish-manageApi'
import { notification } from 'antd'
import moment from 'moment';

function Pubilsh(publishState,auditState,checkPage) {
    const { userName } = JSON.parse(localStorage.getItem("token"))
    const [page,setpage] =  useState(1)
    const [limit,setlimit] =  useState(10)
    // 列表数据
    const [dataSource, setdataSource] = useState([])
    // 表格列表长度
    const [total, setTotal] = useState()
    // 获取列表
    useEffect(() => {
        getArticleList({
            publishState,
            auditState,
            userName: userName,
            page: page || 1,
            limit: limit || 10
        }).then((res) => {
            setdataSource(res.queryPageList.records)
            setTotal(res.queryPageList.total)
        })
    }, [userName, publishState, auditState,page,limit])
    // 发布的回调
    const handlePublish = (id) => {
        setdataSource(dataSource.filter(item => item.pageId !== id))
        updataArticle({
            pageId: id,
            publishState: 1,
            auditState: 1,
            publishTime:moment(Date.now()).format("YYYY-MM-DD HH:mm:ss")
        }).then((res) => {
            notification.info({
                message: `通知`,
                description:
                  `您可以到【发布管理/已经发布】中查看您的新闻`,
                placement:"bottomRight"
            });
        })
     }
    // 删除的回调
    const handleDelete = (id) => { 
        // 过滤到状态里的下线文章
        setdataSource(dataSource.filter(item => item.pageId !== id))
        deleteArticle(id).then(() => { 
            notification.info({
                message: `通知`,
                description:
                  `您已经删除了已下线的新闻`,
                placement:"bottomRight"
            });
        })
    }
    // 下线的回调
    const handleSunset = (id) => { 
        // 过滤到状态里的下线文章
        setdataSource(dataSource.filter(item => item.pageId !== id))
        // 发送请求真正修改数据库中数据
        updataArticle({
            pageId: id,
            publishState:4
        }).then((res) => { 
            notification.info({
                message: `通知`,
                description:
                  `您可以到【发布管理/已下线】中查看您的新闻`,
                placement:"bottomRight"
            });
        })        
    }
    // 控制分页
    const changePage = (page, limit) => { 
        setlimit(limit)
        setpage(page)
    }
    // 自定义hooks把要使用的return出去
    return {
        dataSource,
        total,
        handlePublish,
        handleSunset,
        handleDelete,
        changePage
    }
}
export default Pubilsh